import { ref, onMounted } from 'vue';
import dashboardApi from '@/apis/dashboard';

/**
 * Dashboard页面的业务逻辑Hook
 */
export default function useDashboard() {
  // 统计数据
  const totalCost = ref('¥1,235,642.50');
  const totalRecords = ref(38);
  const departmentCount = ref(8);
  const pendingApprovals = ref(5);
  
  // 部门成本数据（从SQL数据中提取）
  const departmentCostOption = ref({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['技术部', '市场部', '财务部', '人力资源部', '行政部', '销售部', '客服部', '产品部']
    },
    series: [
      {
        name: '部门成本',
        type: 'pie',
        radius: '60%',
        center: ['50%', '50%'],
        data: [
          { value: 306624.33, name: '技术部' },
          { value: 808946.88, name: '市场部' },
          { value: 442780.78, name: '财务部' },
          { value: 996945.83, name: '人力资源部' },
          { value: 817510.09, name: '行政部' },
          { value: 773070.81, name: '销售部' },
          { value: 183218.12, name: '客服部' },
          { value: 858806.55, name: '产品部' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
  
  // 成本项目分析（从SQL数据中提取）
  const costItemOption = ref({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: ['工资薪金', '办公设备', '差旅费', '会议费', '培训费', '水电费', '通讯费', '材料费', '广告费', '招待费']
    },
    series: [
      {
        name: '成本金额',
        type: 'bar',
        data: [
          39826.44,
          42715.80,
          110256.98,
          80534.08,
          55771.62,
          107074.76,
          15908.31,
          105031.54,
          52045.69,
          117526.43
        ]
      }
    ]
  });
  
  // 成本趋势分析
  const costTrendOption = ref({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['实际成本', '预算成本', '预估成本']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '实际成本',
        type: 'line',
        stack: 'Total',
        data: [120000, 190000, 180000, 170000, 160000, 200000, 210000, 220000, 240000, 230000, 0, 0]
      },
      {
        name: '预算成本',
        type: 'line',
        stack: 'Total',
        data: [150000, 150000, 150000, 150000, 150000, 150000, 150000, 150000, 150000, 150000, 150000, 150000]
      },
      {
        name: '预估成本',
        type: 'line',
        stack: 'Total',
        data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 180000, 190000]
      }
    ]
  });
  
  // 月度支出对比图表
  const monthlyExpenseOption = ref({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['今年', '去年']
    },
    xAxis: [
      {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '支出金额',
        min: 0,
        max: 300000,
        interval: 60000,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '同比增长',
        min: -50,
        max: 50,
        interval: 20,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '今年',
        type: 'bar',
        data: [120000, 190000, 180000, 170000, 160000, 200000, 210000, 220000, 240000, 230000, 0, 0]
      },
      {
        name: '去年',
        type: 'bar',
        data: [100000, 160000, 150000, 140000, 130000, 170000, 180000, 190000, 200000, 210000, 190000, 180000]
      },
      {
        name: '同比增长',
        type: 'line',
        yAxisIndex: 1,
        data: [20, 18.75, 20, 21.43, 23.08, 17.65, 16.67, 15.79, 20, 9.52, -94.74, -94.74]
      }
    ]
  });
  
  /**
   * 获取首页统计数据
   */
  const fetchDashboardStats = async () => {
    try {
      const response = await dashboardApi.getDashboardStats();
      if (response.data) {
        const { totalExpense: cost, costItemCount: records, departmentCount: depts, pendingBudgetCount: approvals } = response.data;
        totalCost.value = cost;
        totalRecords.value = records;
        departmentCount.value = depts;
        pendingApprovals.value = approvals;
      }
    } catch (error) {
      console.error('获取首页统计数据失败:', error);
      // 使用默认值，不影响页面显示
    }
  };
  
  /**
   * 获取部门成本分布数据
   */
  const fetchDepartmentCostDistribution = async () => {
    try {
      const response = await dashboardApi.getDepartmentCostDistribution();
      if (response.data && response.data.data) {
        departmentCostOption.value.series[0].data = response.data.data;
        // 更新图例数据
        departmentCostOption.value.legend.data = response.data.data.map(item => item.name);
      }
    } catch (error) {
      console.error('获取部门成本分布数据失败:', error);
      // 使用默认数据
    }
  };
  
  /**
   * 获取成本项目分析数据
   */
  const fetchCostItemAnalysis = async () => {
    try {
      const response = await dashboardApi.getCostItemAnalysis();
      if (response.data && response.data.data) {
        // 假设返回的数据格式为 {name: '项目名', value: 金额} 的数组
        const sortedData = response.data.data.sort((a, b) => b.value - a.value);
        costItemOption.value.yAxis.data = sortedData.map(item => item.name);
        costItemOption.value.series[0].data = sortedData.map(item => item.value);
      }
    } catch (error) {
      console.error('获取成本项目分析数据失败:', error);
      // 使用默认数据
    }
  };
  
  /**
   * 获取成本趋势分析数据
   */
  const fetchCostTrendAnalysis = async () => {
    try {
      const response = await dashboardApi.getCostTrendAnalysis();
      if (response.data && response.data.data) {
        costTrendOption.value.series = response.data.data;
      }
    } catch (error) {
      console.error('获取成本趋势分析数据失败:', error);
      // 使用默认数据
    }
  };
  
  /**
   * 获取月度支出对比数据
   */
  const fetchMonthlyExpenseComparison = async () => {
    try {
      const response = await dashboardApi.getMonthlyExpenseComparison();
      if (response.data && response.data.data) {
        monthlyExpenseOption.value.series = response.data.data;
      }
    } catch (error) {
      console.error('获取月度支出对比数据失败:', error);
      // 使用默认数据
    }
  };
  
  /**
   * 初始化数据
   */
  const initDashboardData = async () => {
    await Promise.all([
      fetchDashboardStats(),
      fetchDepartmentCostDistribution(),
      fetchCostItemAnalysis(),
      fetchCostTrendAnalysis(),
      fetchMonthlyExpenseComparison()
    ]);
  };
  
  // 组件挂载时初始化数据
  onMounted(async () => {
    await initDashboardData();
  });
  
  return {
    // 统计数据
    totalCost,
    totalRecords,
    departmentCount,
    pendingApprovals,
    
    // 图表配置
    departmentCostOption,
    costItemOption,
    costTrendOption,
    monthlyExpenseOption,
    
    // 方法
    initDashboardData,
    fetchDashboardStats,
    fetchDepartmentCostDistribution,
    fetchCostItemAnalysis,
    fetchCostTrendAnalysis,
    fetchMonthlyExpenseComparison
  };
}